import { Component, ElementRef, Injectable, Injector, ViewChild } from '@angular/core';
import { UniversalTablesUtil } from '../../../core/universal-tables.util';
import * as _ from 'lodash';
import { timeout } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';

@Injectable({ providedIn: 'root' })

@Component({
  selector: 'app-construction',
  templateUrl: './construction.component.html',
  styles: [`
      .b-d {padding-bottom:16px;}
  `]
})
export class ConstructionComponent extends UniversalTablesUtil {
  querying = false;
  monthCode = '';
  monthSelected: Date;
  today = new Date().getDate();
  lockHeadScroll = { x: '2000px', y: window.innerHeight - 350 + 'px' };
  @ViewChild('subject', { read: ElementRef, static: true }) subjectC: ElementRef;
  @ViewChild('coordinate', { read: ElementRef, static: true }) coordinateC: ElementRef;

  constructor(
    private injector: Injector,
    private datePipe: DatePipe
  ) {
    super(injector);
  }

  getMainData(rows: number, page: number, others) {
    let newParams: any = this.params;
    this.oldSize = rows;
    if (!_.isEqual(newParams, others)) {
      newParams = { ...newParams, ...others };
      this.isGetAll = false;
    }
    if (_.isEmpty(others)) {
      this.params = others;
      this.isGetAll = true;
    }
    if (others.hasOwnProperty('ispeihe')) {
      delete newParams.monthCode;
    }
    if (others.hasOwnProperty('monthCode')) {
      delete newParams.ispeihe;
    }
    this.params = newParams;
    this.pageIndex = page;
    this.loadingData = true;
    this._sub = this.apiService.materialsData(this.apiIdentity, { ...{ rows }, ...{ page }, ...newParams })
      .pipe(timeout(15000))
      .subscribe(res => {
        if (!_.isEmpty(res)) {
          this.itemsTotal = res.totalCount;
          this.displayData = res.data;
          this.allowEdit = _.isNil(res.modifyRight) ? 1 : res.modifyRight;
          this.loadingData = false;
          this.refreshStatus();
        }
      }, err => this.errorHandle(err));
  }

  import() {
    const param: any = {};
    param.vcDate = this.datePipe.transform(this.monthSelected as Date, 'yyyy-MM');
    this.loadingData = true;
    this.constructionImport(param).subscribe(res => {
      if (!_.isEmpty(res)) {
        this.getMainData(this.pageSize, this.pageIndex, this.params);
        this.loadingData = false;
      }
    }, err => this.errorHandle(err));
  }

  // 施工月计划导入
  constructionImport(param) {
    const url = environment.apiBase + '/csmis/constructMonthPlans/impdata.jwt';
    return this.http.get(url, param);
  }

  construction(ispeihe: number) {
    // ispeihe ? this.switchColor('bg-blue-3', 'bg-green-5') : this.switchColor('bg-green-5', 'bg-blue-3');
    this.getMainData(this.pageSize, this.pageIndex, { ispeihe });
    this.monthCode = '';
  }


}

